package com.example.myapplication.api

import android.util.Log
import com.example.myapplication.data.Stock
import com.example.myapplication.data.StockPrice
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
import java.text.SimpleDateFormat
import java.util.*

/**
 * 腾讯财经API - 历史K线数据
 * 测试通过 ✅ - 2025-10-10
 */
class TencentFinanceApi {
    
    companion object {
        private const val TAG = "TencentFinanceApi"
        private const val BASE_URL = "https://web.ifzq.gtimg.cn/appstock/app/fqkline/get"
        private const val TIMEOUT = 10000
    }
    
    /**
     * 获取历史K线数据
     * 
     * @param symbol 股票代码（带sh/sz前缀，如sh600519）
     * @param days 获取天数（默认90天）
     * @return K线数据列表
     */
    suspend fun getHistoryData(symbol: String, days: Int = 90): List<StockPrice> {
        return withContext(Dispatchers.IO) {
            try {
                // 构建请求参数
                // 格式: sh600519,day,,,30,qfq
                // 参数说明: 股票代码,day,起始日期,结束日期,数据条数,复权方式
                val param = "$symbol,day,,,$days,qfq"
                val encodedParam = URLEncoder.encode(param, "UTF-8")
                
                val urlString = "$BASE_URL?param=$encodedParam&_var=kline_dayqfq"
                
                Log.d(TAG, "请求历史数据: $urlString")
                
                val url = URL(urlString)
                val connection = url.openConnection() as HttpURLConnection
                
                connection.apply {
                    requestMethod = "GET"
                    connectTimeout = TIMEOUT
                    readTimeout = TIMEOUT
                    
                    // 重要: 添加请求头，否则会被拒绝
                    setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
                    setRequestProperty("Referer", "https://gu.qq.com/")
                }
                
                val responseCode = connection.responseCode
                Log.d(TAG, "响应状态码: $responseCode")
                
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    val reader = BufferedReader(InputStreamReader(connection.inputStream, "UTF-8"))
                    val response = reader.readText()
                    reader.close()
                    
                    Log.d(TAG, "响应内容前100字符: ${response.take(100)}")
                    
                    // 解析JSONP格式: kline_dayqfq={...JSON...}
                    val jsonStr = if (response.contains("kline_dayqfq=")) {
                        response.substringAfter("kline_dayqfq=")
                    } else {
                        response
                    }
                    
                    val jsonObject = JSONObject(jsonStr)
                    
                    if (jsonObject.has("data") && !jsonObject.isNull("data")) {
                        val dataObject = jsonObject.getJSONObject("data")
                        
                        if (dataObject.has(symbol)) {
                            val symbolObject = dataObject.getJSONObject(symbol)
                            
                            if (symbolObject.has("qfqday")) {
                                val klineArray = symbolObject.getJSONArray("qfqday")
                                val result = mutableListOf<StockPrice>()
                                
                                for (i in 0 until klineArray.length()) {
                                    val klineStr = klineArray.getString(i)
                                    val parts = klineStr.split(",")
                                    
                                    // 数据格式: [日期, 开, 收, 高, 低, 成交量]
                                    if (parts.size >= 6) {
                                        try {
                                            val date = parts[0]  // 格式: 2025-08-22
                                            val open = parts[1].toDouble()
                                            val close = parts[2].toDouble()
                                            val high = parts[3].toDouble()
                                            val low = parts[4].toDouble()
                                            val volume = parts[5].toLongOrNull() ?: 0L
                                            
                                            result.add(
                                                StockPrice(
                                                    date = date,
                                                    open = open,
                                                    close = close,
                                                    high = high,
                                                    low = low,
                                                    volume = volume
                                                )
                                            )
                                        } catch (e: Exception) {
                                            Log.e(TAG, "解析K线数据失败: ${e.message}")
                                        }
                                    }
                                }
                                
                                Log.d(TAG, "成功获取 ${result.size} 条历史数据")
                                return@withContext result
                            }
                        }
                    }
                    
                    Log.w(TAG, "数据格式不正确或为空")
                } else {
                    Log.e(TAG, "请求失败，状态码: $responseCode")
                }
                
                connection.disconnect()
                
            } catch (e: Exception) {
                Log.e(TAG, "获取历史数据异常: ${e.message}", e)
            }
            
            emptyList()
        }
    }
    
    /**
     * 规范化股票代码
     * 600519 -> sh600519
     * 000858 -> sz000858
     */
    fun normalizeSymbol(symbol: String): String {
        val clean = symbol.trim()
        
        // 如果已经有前缀，直接返回
        if (clean.startsWith("sh") || clean.startsWith("sz")) {
            return clean
        }
        
        // 根据代码判断市场
        return when {
            clean.startsWith("6") -> "sh$clean"  // 上海主板
            clean.startsWith("0") -> "sz$clean"  // 深圳主板
            clean.startsWith("3") -> "sz$clean"  // 创业板
            clean.startsWith("2") -> "sz$clean"  // 深圳B股
            else -> clean
        }
    }
}

